package cn.edu.huanu.service.impl;

import cn.edu.huanu.dao.UserDao;
import cn.edu.huanu.dao.impl.UserDaoImpl;
import cn.edu.huanu.exception.BusinessException;
import cn.edu.huanu.exception.DaoException;
import cn.edu.huanu.pojo.User;
import cn.edu.huanu.service.UserService;
import cn.edu.huanu.utils.R;

/**
 * @author hb
 * @date 2025-11-06 10:57:28
 */
public class UserServiceImpl implements UserService {
    //业务逻辑的实现依赖数据访问层
    private UserDao userDao=new UserDaoImpl();

    @Override
    public R checkUserNameExist(String username) throws BusinessException {
        //对username的格式进行校验
        User user = userDao.queryUserByUserName(username);
        R r =new R();
        if(user!=null){
            r.setMessage("用户名已经存在");
            r.setSuccess(false);
            r.setCode(401202);
        }else{
            r.setMessage("用户名可以使用");
            r.setSuccess(true);
            r.setCode(200301);
        }
        return r;
    }

    @Override
    public User login(String username, String pwd) throws BusinessException {
        //对username,pwd的格式进行校验

        User user = userDao.queryUserByUsernameAndPwd(username, pwd);
        if(user==null){
            throw new BusinessException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public R regiester(User user) throws BusinessException {
        R r=new R();
        try {
            //对username,pwd（密码长度不能少于六位）的格式进行校验
            //对用户名进行唯一性校验
            User u= userDao.queryUserByUserName(user.getUsername());
            if(u!=null){
                throw new BusinessException("用户名已存在");
            }
            userDao.insertUser(user);
            r.success() ;
        }catch(BusinessException e){
             r.error().setMessage(e.getMessage());
        } catch (Exception e){
            r.error().setMessage("服务器繁忙!");
        }

        return r;

    }
}
